package cn.easyutil.veteran.core.utils;

import java.math.BigDecimal;

/**
 * 数学计算
 * @author spc
 *
 */
public class NumberCalcUtil {
	
	private BigDecimal value;

	private int digits = 2;

	private boolean rounding = true;

	public static NumberCalcUtil of(Number number, int digits){
		return new NumberCalcUtil(number,digits);
	}
	public static NumberCalcUtil of(Number number){
		return new NumberCalcUtil(number,2);
	}
	public NumberCalcUtil(Number number, int digits, boolean rounding){
		this.digits = digits;
		this.rounding = rounding;
		this.value = BigDecimal.valueOf(number.doubleValue());
	}

	public NumberCalcUtil(Number number, int digits){
		this(number,digits,false);
	}
	
	/**
	 * 加法运算
	 */
	public NumberCalcUtil addition(Number a){
		this.value = this.value.add(BigDecimal.valueOf(a.doubleValue())).setScale(digits,rounding?BigDecimal.ROUND_HALF_UP:BigDecimal.ROUND_DOWN);
		return this;
	}
	
	public BigDecimal getResult(){
		return this.value.setScale(digits,rounding?BigDecimal.ROUND_HALF_UP:BigDecimal.ROUND_DOWN);
	}


	
	/**
	 * 减法运算
	 */
	public NumberCalcUtil subtraction(Number a){
		this.value = this.value.subtract(BigDecimal.valueOf(a.doubleValue())).setScale(digits,rounding?BigDecimal.ROUND_HALF_UP:BigDecimal.ROUND_DOWN);
		return this;
	}
	
	/**
	 * 乘法运算
	 */
	public NumberCalcUtil multiply(Number a){
		if(a.doubleValue() == 0){
			this.value = new BigDecimal(0);
			return this;
		}
		this.value = this.value.multiply(BigDecimal.valueOf(a.doubleValue())).setScale(digits,rounding?BigDecimal.ROUND_HALF_UP:BigDecimal.ROUND_DOWN);
		return this;
	}
	
	/**
	 * 除法运算
	 */
	public NumberCalcUtil divide(Number a){
		if(a.doubleValue() == 0){
			this.value = new BigDecimal(0);
			return this;
		}
		this.value = this.value.divide(BigDecimal.valueOf(a.doubleValue()),digits,rounding?BigDecimal.ROUND_HALF_UP:BigDecimal.ROUND_DOWN);
		return this;
	}

}
